package com.ruoyi.miniapp.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.wxiaoqi.security.common.tool.ToolPager;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.miniapp.ali.QrUtil;
import com.ruoyi.miniapp.ali.UUIDUtil;
import com.ruoyi.miniapp.config.BucketNameConfig;
import com.ruoyi.miniapp.domain.BasMaintainerApply;
import com.ruoyi.miniapp.domain.ResItem;
import com.ruoyi.miniapp.domain.ResType;
import com.ruoyi.miniapp.dto.ApplyUserDto;
import com.ruoyi.miniapp.dto.ArgumentsDto;
import com.ruoyi.miniapp.dto.TrainingAddressDto;
import com.ruoyi.miniapp.mapper.BasMaintainerApplyMapper;
import com.ruoyi.miniapp.mapper.TrainingAddressMapper;
import com.ruoyi.miniapp.service.IBasMaintainerApplyService;
import com.ruoyi.miniapp.service.IRealNameAuthInfoService;
import com.ruoyi.miniapp.service.IResItemService;
import com.ruoyi.miniapp.service.IResTypeService;
import com.ruoyi.system.api.model.RealNameAuthInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import static com.ruoyi.miniapp.ali.ImageBufTool.getFileSizeWithM;
import static com.ruoyi.miniapp.ali.OSSKeyUtil.combineOSSKey;
import static com.ruoyi.miniapp.ali.OSSKeyUtil.getFullPath;

/**
 * 表名：BAS_MAINTAINER_APPLY 	 说明：用户报名表 
 */
@Slf4j
@Service
public class BasMaintainerApplyServiceImpl implements IBasMaintainerApplyService {

	private Logger logger = LogManager.getLogger(this.getClass());

	@Autowired
	private BasMaintainerApplyMapper maintainerApplyMapper;

	@Autowired
	private TrainingAddressMapper trainingAddressMapper;

	@Autowired
	private IRealNameAuthInfoService realNameAuthInfoService;

	@Autowired
	private OSSClient ossClient;

	@Autowired
	BucketNameConfig bucketNameConfig;

	@Autowired
	IResTypeService resTypeService;
	@Autowired
	IResItemService resItemService;
	/**
	 * 签到
	 * @param obj
	 * @return
	 */
	@Override
	public AjaxResult updateBasMaintainerApplyByUserId(BasMaintainerApply obj) {
//		Long userId = SecurityUtils.getUserId();
//		obj.setUserId(userId);
		Integer count = maintainerApplyMapper.updateBasMaintainerApplyByUserId(obj);
		if (count > 0){
			return AjaxResult.success("签到成功");
		}else{
			return AjaxResult.success("签到失败");
		}
	}


	/**
	 * 将二维码保存为资源接口
	 * @param resName
	 * @param content
	 * @param width
	 * @param height
	 * @return
	 */
	@Override
	public AjaxResult save(String resName,String content,int width,int height)
	{
		Long tempTypeVal = 101L;
		int dtFileTypeNo =22;
		String uuid = null;
		String username = SecurityUtils.getUsername();
		Long userId = SecurityUtils.getUserId();
		if(userId == null || userId == 0){
			return AjaxResult.error("操作前请先登录");
		}
		uuid = UUIDUtil.createId();
		ResType resType = resTypeService.selectResTypeByPkResTypeId((long) tempTypeVal);
		String fileName = uuid + ".png";
		String fullPath = getFullPath(resType.getFullPath(), userId, username);
		String fullUrl = getFullPath(bucketNameConfig.getBaseUrl(tempTypeVal), fullPath, fileName);
//        String fullPath = getFullPath(bucketNameConfig.getBaseUrl((long)tempTypeVal), resType.getFullPath(), fileName);
		//todo 需要获取用户信息
		Long size = null;

		try(InputStream image = QrUtil.createQRCode(width, height, content)){
			size = Long.valueOf(image.available());
			String bukName = bucketNameConfig.getBucketName((long) tempTypeVal);
			PutObjectResult putObjectResult = ossClient.putObject(bukName, combineOSSKey(fullPath, fileName), image);
		}catch(Exception e)
		{
			return AjaxResult.error("保存二维码失败"+e.getLocalizedMessage());
		}
		ResItem item = new ResItem();
		item.setPkResId(uuid);
		item.setResName(resName);
		item.setImgHeight(height);
		item.setImgWidth(width);
		item.setFileFullPath(fullUrl);
		item.setOriginFileName(fileName);
		item.setFkOwnerUid(userId);// (String) userIdResult.getData());
		item.setFkResTypeId((long) tempTypeVal);
		item.setSize(getFileSizeWithM(size));
		//                item.setCreateTime(new Date());
		item.setDtFileTypeNo(dtFileTypeNo);
		int i = resItemService.insertResItem(item);
		if(i > 0){
			return AjaxResult.success("保存成功", item);
		}else {
			if(ObjectUtils.isNotEmpty(uuid)){
				try{
					resItemService.deleteResItemByPkResId(uuid);
				}catch(Exception e){
					log.warn(e.getLocalizedMessage());
				}
			}
			resItemService.deleteResItemByPkResId(uuid);
			return AjaxResult.error("保存图片失败");
		}
	}

	/**
	 * 运维后台
	 * #根据场次查询用户信息
	 * @return
	 */
	@Override
	public AjaxResult getUserInfoList(ArgumentsDto obj) {
		// 分页实现
		if(obj.getCurrentPage() == null || obj.getCurrentPage() <= 0){
			obj.setCurrentPage(1);
		}
		if(obj.getPageSize() == null || obj.getPageSize() <= 0){
			obj.setPageSize(ToolPager.DEFAULT_PAGE_SIZE);
		}
		List<String> StudentList = new ArrayList<>();
		List<String> selStudentListA = trainingAddressMapper.selApplyIdListA(obj.getId());
		List<String> selStudentListB = trainingAddressMapper.selApplyIdListB(obj.getId());
		StudentList.addAll(selStudentListA);
		StudentList.addAll(selStudentListB);
		obj.setKeys(StudentList);
		List<ApplyUserDto> userInfo = new ArrayList<>();
		if (obj.getKeys().size() <= 0){
			return AjaxResult.success(new TableDataInfo(userInfo,0));
		}else {
			userInfo = maintainerApplyMapper.getUserInfo(obj);
			//查询总数
			Integer userInfoCount = maintainerApplyMapper.getUserInfoCount(obj);
			for (ApplyUserDto userDto : userInfo) {
				Long userId = userDto.getUserId();
				RealNameAuthInfo realNameAuthInfo = realNameAuthInfoService.selRealNameAuth(userId);
				userDto.setUserName(realNameAuthInfo.getRealName());
				userDto.setUserPhone(realNameAuthInfo.getTel());
			}
			return AjaxResult.success(new TableDataInfo(userInfo,userInfoCount));
		}
	}

	/**
	 * 获取最大序列码
	 * @param key
	 * @return
	 */
	@Override
	public String getCertificateNo(Integer key) {
		return maintainerApplyMapper.getCertificateNo(key);
	}

	/**
	 * 根据userid查询用户信息
	 * Userid
	 * @return
	 */
	@Override
	public BasMaintainerApply getBasMaintainerApplyByUserId() {
		Long userId = SecurityUtils.getUserId();
		BasMaintainerApply maintainerApply = maintainerApplyMapper.getBasMaintainerApplyByUserId(userId);
//		RealNameAuthInfo realNameAuthInfo = realNameAuthInfoService.selRealNameAuth(userId);
//		if (maintainerApply.getNewAddress() == null ){
//			TrainingAddressDto trainingAddressByKey = trainingAddressMapper.getTrainingAddressByKey(maintainerApply.getAddressId());
//			trainingAddressByKey.setUserName(realNameAuthInfo.getRealName());
//			trainingAddressByKey.setUserPhone(realNameAuthInfo.getTel());
//			trainingAddressByKey.setApplyId(maintainerApply.getApplyId());
//		}else {
//			TrainingAddressDto trainingAddressByKey = trainingAddressMapper.getTrainingAddressByKey(maintainerApply.getNewAddress());
//			trainingAddressByKey.setUserName(realNameAuthInfo.getRealName());
//			trainingAddressByKey.setUserPhone(realNameAuthInfo.getTel());
//			trainingAddressByKey.setApplyId(maintainerApply.getApplyId());
//		}
		return maintainerApply;
	}

	/**
	 * 根据userid查询用户信息
	 * Userid
	 * @return
	 */
	@Override
	public BasMaintainerApply getBasMaintainerApplyByUserIdNoPay(Long userId) {
//		Long userId = SecurityUtils.getUserId();
		BasMaintainerApply maintainerApply = maintainerApplyMapper.getBasMaintainerApplyByUserIdNoPay(userId);
		return maintainerApply;
	}

	/**
	 * 增加
	 */
	@Override
	public int insertBasMaintainerApply(BasMaintainerApply obj){
		int count = maintainerApplyMapper.insertBasMaintainerApply(obj);
		logger.info("BAS_MAINTAINER_APPLY表插入"+count+"条数据;KEY="+obj.getApplyId());
		return count;
	}

	/**
	 * 查询count
	 */
	@Override
	public int getBasMaintainerApplyCount(BasMaintainerApply obj){
		int count = maintainerApplyMapper.getBasMaintainerApplyCount(obj);
		return count;
	}

	/**
	 * 查询List
	 */
	@Override
	public List<BasMaintainerApply> getBasMaintainerApplyList(BasMaintainerApply obj){
		List<BasMaintainerApply> objList = maintainerApplyMapper.getBasMaintainerApplyList(obj);
		return objList;
	}

	/**
	 * 分页查询
	 */
	@Override
	public ToolPager<BasMaintainerApply> getPageBasMaintainerApply(BasMaintainerApply obj){
		if(null == obj.getCurrentPage() || obj.getCurrentPage() <= 0 ){
			obj.setCurrentPage(1);
		}
		if(null == obj.getPageSize() || obj.getPageSize() <= 0 ){
			obj.setPageSize(ToolPager.DEFAULT_PAGE_SIZE);
		}
		int count = maintainerApplyMapper.getBasMaintainerApplyCount(obj);
		List<BasMaintainerApply> objList = maintainerApplyMapper.getBasMaintainerApplyList(obj);
		return new ToolPager<BasMaintainerApply>(count, objList, obj.getCurrentPage(), obj.getPageSize());
	}

	/**
	 * 主键查询
	 */
	@Override
	public BasMaintainerApply getBasMaintainerApplyByKey(String key) {
		return maintainerApplyMapper.getBasMaintainerApplyByKey(key);
	}

	/**
	 * 主键查询
	 */
	@Override
	public BasMaintainerApply getBasMaintainerApplyByOrderNum(String orderNum) {
		return maintainerApplyMapper.getBasMaintainerApplyByOrderNum(orderNum);
	}

	/**
	 * 多主键查询
	 */
	@Override
	public List<BasMaintainerApply> getBasMaintainerApplyByKeys(List<Long> key) {
		return maintainerApplyMapper.getBasMaintainerApplyByKeys(key);
	}

	/**
	 * 修改
	 */
	@Override
	public int updateBasMaintainerApply(BasMaintainerApply obj){
		int count = maintainerApplyMapper.updateBasMaintainerApply(obj);
		return count;
	}

	/**
	 * 删除
	 */
	@Override
	public int deleteBasMaintainerApply(String key){
		int count = maintainerApplyMapper.deleteBasMaintainerApply(key);
		return count;
	}

	/**
	 * 批量增加
	 */
	@Override
	public int batchInsertBasMaintainerApply(List<BasMaintainerApply> objList){
		int count = maintainerApplyMapper.batchInsertBasMaintainerApply(objList);
		logger.info("BAS_MAINTAINER_APPLY成功插入"+count+"条数据");
		return count;
	}

	/**
	 * 批量修改
	 */
	@Override
	public int batchUpdateBasMaintainerApply(List<BasMaintainerApply> objList){
		int count = maintainerApplyMapper.batchUpdateBasMaintainerApply(objList);
		logger.info("BAS_MAINTAINER_APPLY成功更新"+count+"条数据");
		return count;
	}

	/**
	 * 批量删除
	 */
	@Override
	public int batchDeleteBasMaintainerApply(List<Long> keys){
		int count = maintainerApplyMapper.batchDeleteBasMaintainerApply(keys);
		logger.info("BAS_MAINTAINER_APPLY成功删除"+count+"条数据");
		return count;
	}

}